package cn.bertsir.qrtest.slice;

import cn.bertsir.qrtest.ResourceTable;
import cn.bertsir.zbar.Qr.ScanResult;
import cn.bertsir.zbar.QrConfig;
import cn.bertsir.zbar.QrManager;
import cn.bertsir.zbar.utils.QRUtils;
import cn.bertsir.zbar.view.ScanLineView;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.colors.RgbPalette;
import ohos.agp.components.*;
import ohos.agp.utils.Color;
import ohos.agp.window.dialog.ToastDialog;
import ohos.global.resource.NotExistException;
import ohos.global.resource.Resource;
import ohos.global.resource.ResourceManager;
import ohos.global.resource.WrongTypeException;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;

import java.io.IOException;

public class MainAbilitySlice extends AbilitySlice implements Component.ClickedListener {
    private static final String TAG = "MainAbilitySlice";
    private Image iv_qr;
    private Button bt_make;
    private TextField et_qr_content;
    private TextField et_qr_title;
    private TextField et_qr_des;
    private Checkbox cb_show_title;
    private Checkbox cd_show_des;
    private Checkbox cb_show_ding;
    private Checkbox cb_show_custom_ding;
    private Checkbox cb_show_flash;
    private Checkbox cb_show_album;
    private Checkbox cb_only_center;
    private Checkbox cb_create_add_water;
    private Checkbox cb_crop_image;
    private Checkbox cb_show_zoom;
    private Checkbox cb_auto_zoom;
    private Checkbox cb_finger_zoom;
    private Checkbox cb_double_engine;
    private Checkbox cb_loop_scan;
    private Checkbox cb_auto_light;
    private Checkbox cb_have_vibrator;
    private RadioButton rb_qrcode;
    private RadioButton rb_bcode;
    private RadioButton rb_all;
    private RadioButton rb_screen_sx;
    private RadioButton rb_screen_hx;
    private RadioButton rb_screen_auto;
    private TextField et_loop_scan_time;
    private RadioButton rb_scanline_radar;
    private RadioButton rb_scanline_grid;
    private RadioButton rb_scanline_hybrid;
    private RadioButton rb_scanline_line;


    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);

    }

    @Override
    protected void onActive() {
        super.onActive();
        initView();
    }

    private void initView() {
        findComponentById(ResourceTable.Id_bt_scan).setClickedListener(this);
        iv_qr = (Image) findComponentById(ResourceTable.Id_iv_qr);
        iv_qr.setClickedListener(this);
        bt_make = (Button) findComponentById(ResourceTable.Id_bt_make);
        bt_make.setClickedListener(this);
        iv_qr.setLongClickedListener(new Component.LongClickedListener() {
            @Override
            public void onLongClicked(Component component) {
                String string = null;
                try {
                    string = QRUtils.getInstance().decodeQRcode(iv_qr);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                ToastDialog toastDialog = new ToastDialog(getContext());
                toastDialog.setSize(DirectionalLayout.LayoutConfig.MATCH_CONTENT, DirectionalLayout.LayoutConfig.MATCH_CONTENT);
                toastDialog.setText("内容：" +string);
                Text toastText=(Text) toastDialog.getComponent();
                if(toastText!=null)
                {
                    toastText.setMultipleLine(true);
                    toastText.setTextSize(14, Text.TextSizeType.FP);
                    toastText.setPaddingBottom(20);
                    toastText.setPaddingTop(20);
                }
                toastDialog.show();
            }
        });
        et_qr_content = (TextField) findComponentById(ResourceTable.Id_et_qr_content);
        et_qr_title = (TextField) findComponentById(ResourceTable.Id_et_qr_title);
        et_qr_des = (TextField) findComponentById(ResourceTable.Id_et_qr_des);
        cb_show_title = (Checkbox) findComponentById(ResourceTable.Id_cb_show_title);
        cd_show_des = (Checkbox) findComponentById(ResourceTable.Id_cd_show_des);
        cb_show_ding = (Checkbox) findComponentById(ResourceTable.Id_cb_show_ding);
        cb_show_custom_ding = (Checkbox) findComponentById(ResourceTable.Id_cb_show_custom_ding);
        cb_show_flash = (Checkbox) findComponentById(ResourceTable.Id_cb_show_flash);
        cb_show_album = (Checkbox) findComponentById(ResourceTable.Id_cb_show_album);
        cb_only_center = (Checkbox) findComponentById(ResourceTable.Id_cb_only_center);
        cb_crop_image = (Checkbox) findComponentById(ResourceTable.Id_cb_crop_image);
        cb_create_add_water = (Checkbox) findComponentById(ResourceTable.Id_cb_create_add_water);
        cb_show_zoom = (Checkbox) findComponentById(ResourceTable.Id_cb_show_zoom);
        cb_auto_zoom = (Checkbox) findComponentById(ResourceTable.Id_cb_auto_zoom);
        cb_finger_zoom = (Checkbox) findComponentById(ResourceTable.Id_cb_finger_zoom);
        cb_double_engine = (Checkbox) findComponentById(ResourceTable.Id_cb_double_engine);
        cb_loop_scan = (Checkbox) findComponentById(ResourceTable.Id_cb_loop_scan);
        rb_qrcode = (RadioButton) findComponentById(ResourceTable.Id_rb_qrcode);
        rb_bcode = (RadioButton) findComponentById(ResourceTable.Id_rb_bcode);
        rb_all = (RadioButton) findComponentById(ResourceTable.Id_rb_all);
        rb_screen_hx = (RadioButton) findComponentById(ResourceTable.Id_rb_screen_hx);
        rb_screen_sx = (RadioButton) findComponentById(ResourceTable.Id_rb_screen_sx);
        rb_screen_auto = (RadioButton) findComponentById(ResourceTable.Id_rb_screen_auto);
        et_loop_scan_time = (TextField) findComponentById(ResourceTable.Id_et_loop_scan_time);
        rb_qrcode.setChecked(true);
        rb_screen_sx.setChecked(true);
        rb_scanline_radar = (RadioButton) findComponentById(ResourceTable.Id_rb_scanline_radar);
        rb_scanline_radar.setClickedListener(this);
        rb_scanline_grid = (RadioButton) findComponentById(ResourceTable.Id_rb_scanline_grid);
        rb_scanline_grid.setClickedListener(this);
        rb_scanline_hybrid = (RadioButton) findComponentById(ResourceTable.Id_rb_scanline_hybrid);
        rb_scanline_hybrid.setClickedListener(this);
        rb_scanline_line = (RadioButton) findComponentById(ResourceTable.Id_rb_scanline_line);
        rb_scanline_line.setClickedListener(this);
        rb_scanline_line.setChecked(true);
        cb_auto_light = (Checkbox) findComponentById(ResourceTable.Id_cb_auto_light);
        cb_have_vibrator = (Checkbox) findComponentById(ResourceTable.Id_cb_have_vibrator);
    }

    @Override
    public void onClick(Component component) {
        switch (component.getId()) {
            case ResourceTable.Id_bt_scan:
             start();
                break;
            case ResourceTable.Id_bt_make:
                PixelMap qrCode = null;
                if (cb_create_add_water.isChecked()) {
                    try {
                        ResourceManager manager = getResourceManager();
                        String mediaPath = getResourceManager().getMediaPath(ResourceTable.Media_icon);
                        Resource resource1 = null;
                        resource1 = manager.getRawFileEntry(mediaPath).openRawFile();
                        ImageSource.SourceOptions sourceOptions = new ImageSource.SourceOptions();
                        ImageSource imageSource = ImageSource.create(resource1, sourceOptions);
                        PixelMap pixelMap = imageSource.createPixelmap(null);
                        qrCode = QRUtils.getInstance().createQRCodeAddLogo(et_qr_content.getText().toString(),
                                pixelMap);
                    } catch (IOException e) {
                        e.printStackTrace();
                    } catch (NotExistException e) {
                        e.printStackTrace();
                    } catch (WrongTypeException e) {
                        e.printStackTrace();
                    }
                } else {
                    qrCode = QRUtils.getInstance().createQRCode(et_qr_content.getText().toString());
//                    QRUtils.TextViewConfig textViewConfig = new QRUtils.TextViewConfig();
//                    textViewConfig.setSize(10);
//                    qrCode=QRUtils.getInstance().createBarCodeWithText(getContext(),"123456789",300,100,textViewConfig);
                }
                iv_qr.setPixelMap(qrCode);
                new ToastDialog(getContext()).setText("长按可识别").show();
                break;
            default:
                break;
        }
    }

    private void start() {
        int scan_type = 1;
        int scan_view_type = 0;
        int screen = 1;
        int line_style = ScanLineView.style_line;
        if (rb_all.isChecked()) {
            scan_type = QrConfig.TYPE_ALL;
            scan_view_type = QrConfig.SCANVIEW_TYPE_QRCODE;
        } else if (rb_qrcode.isChecked()) {
            scan_type = QrConfig.TYPE_QRCODE;
            scan_view_type = QrConfig.SCANVIEW_TYPE_QRCODE;
        } else if (rb_bcode.isChecked()) {
            scan_type = QrConfig.TYPE_BARCODE;
            scan_view_type = QrConfig.SCANVIEW_TYPE_BARCODE;
        }
        if (rb_screen_auto.isChecked()) {
            screen = QrConfig.SCREEN_SENSOR;
        } else if (rb_screen_sx.isChecked()) {
            screen = QrConfig.SCREEN_PORTRAIT;
        } else if (rb_screen_hx.isChecked()) {
            screen = QrConfig.SCREEN_LANDSCAPE;
        }

        if (rb_scanline_radar.isChecked()) {
            line_style = ScanLineView.style_radar;
        } else if (rb_scanline_grid.isChecked()) {
            line_style = ScanLineView.style_gridding;
        } else if (rb_scanline_hybrid.isChecked()) {
            line_style = ScanLineView.style_hybrid;
        } else if (rb_scanline_line.isChecked()) {
            line_style = ScanLineView.style_line;
        }


        QrConfig qrConfig = new QrConfig.Builder()
                .setDesText(et_qr_des.getText().toString())// 扫描框下文字
                .setShowDes(cd_show_des.isChecked())// 是否显示扫描框下面文字
                .setShowLight(cb_show_flash.isChecked())// 显示手电筒按钮
                .setShowTitle(cb_show_title.isChecked())// 显示Title
                .setShowAlbum(cb_show_album.isChecked())// 显示从相册选择按钮
                .setNeedCrop(cb_crop_image.isChecked())// 是否从相册选择后裁剪图片
                .setCornerColor(RgbPalette.parse("#E42E30"))// 设置扫描框颜色
                .setLineColor(RgbPalette.parse("#E42E30"))// 设置扫描线颜色
                .setLineSpeed(QrConfig.LINE_MEDIUM)// 设置扫描线速度
                .setScanType(scan_type)// 设置扫码类型（二维码，条形码，全部，自定义，默认为二维码）
                .setScanViewType(scan_view_type)// 设置扫描框类型（二维码还是条形码，默认为二维码）
                .setCustombarcodeformat(QrConfig.BARCODE_PDF417)// 此项只有在扫码类型为TYPE_CUSTOM时才有效
                .setPlaySound(cb_show_ding.isChecked())// 是否扫描成功后bi~的声音
                .setDingPath(cb_show_custom_ding.isChecked() ? "resources/rawfile/test.mp3"
                        : "resources/rawfile/qrcode.mp3")// 设置提示音(不设置为默认的Ding~)
                .setIsOnlyCenter(cb_only_center.isChecked())// 是否只识别框中内容(默认为全屏识别)
                .setTitleText(et_qr_title.getText().toString())// 设置Tilte文字
                .setTitleBackgroudColor(RgbPalette.parse("#262020"))// 设置状态栏颜色
                .setTitleTextColor(Color.WHITE.getValue())// 设置Title文字颜色
                .setShowZoom(cb_show_zoom.isChecked())// 是否开始滑块的缩放
                .setAutoZoom(cb_auto_zoom.isChecked())// 是否开启自动缩放(实验性功能，不建议使用)
                .setFingerZoom(cb_finger_zoom.isChecked())// 是否开始双指缩放
                .setDoubleEngine(cb_double_engine.isChecked())// 是否开启双引擎识别(仅对识别二维码有效，并且开启后只识别框内功能将失效)
                .setScreenOrientation(screen)// 设置屏幕方式
                .setOpenAlbumText("选择要识别的图片")// 打开相册的文字
                .setLooperScan(cb_loop_scan.isChecked())// 是否连续扫描二维码
                .setLooperWaitTime(Integer.parseInt(et_loop_scan_time.getText().toString()) * 1000)// 连续扫描间隔时间
                .setScanLineStyle(line_style)// 扫描线样式
                .setAutoLight(cb_auto_light.isChecked())// 自动灯光
                .setShowVibrator(cb_have_vibrator.isChecked())// 是否震动提醒
                .create();
        QrManager.getInstance().init(qrConfig).startScan(MainAbilitySlice.this, new QrManager.OnScanResultCallback() {
            @Override
            public void onScanSuccess(ScanResult rs) {
                getUITaskDispatcher().asyncDispatch(new Runnable() {
                    @Override
                    public void run() {
                        ToastDialog toastDialog = new ToastDialog(getContext());
                        toastDialog.setSize(DirectionalLayout.LayoutConfig.MATCH_CONTENT, DirectionalLayout.LayoutConfig.MATCH_CONTENT);
                        toastDialog.setText(rs.getContent());
                        Text toastText=(Text) toastDialog.getComponent();
                        if(toastText!=null)
                        {
                            toastText.setMultipleLine(true);
                            toastText.setTextSize(14, Text.TextSizeType.FP);
                            toastText.setPaddingBottom(20);
                            toastText.setPaddingTop(20);
                        }
                        toastDialog.show();
                    }
                });
            }
        });
    }
}
